package com.create.myworld.sse;

import com.create.myworld.config.TopicRabbitConfig;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zcw
 * 死亡记录推送
 */
@RequestMapping(value = "/die")
@RestController
@RabbitListener(queues = TopicRabbitConfig.dieKey)
public class DieSSE extends SSE {

    public static List<String> contentList = new ArrayList();

    @SneakyThrows
    @RabbitHandler
    @Override
    public synchronized void push(String content) {
        Thread.sleep(100);
        if (null == content) {
            /**
             * 新连接,推送全部消息
             */
            sseEmitterMap.entrySet().forEach((entry) -> {
                contentList.forEach((history) -> {
                    if (!entry.getKey().contains(dieKey)) {
                        return;
                    }
                    try {
                        entry.getValue().send("history:" + history);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            });
        } else {
            contentList.add(content);
            /**
             * 推送单条消息
             */
            sseEmitterMap.entrySet().forEach((entry) -> {
                if (!entry.getKey().contains(dieKey)) {
                    return;
                }
                try {
                    entry.getValue().send(content);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
